interface SearchServiceResData<T> {
  code: number
  data: {
    current_page: number
    data: T[]
    last_page: number
    per_page: string
    total: number
    [key: string]: any
  }
  msg: string
  time: string
}

type SearchService<T> = () => Promise<SearchServiceResData<T>>

interface UseSearchOptions extends AnyObject {
  dataKeyName: string
}

/**
 * @description 模仿 useLoadMore，将搜索状态与结果封装在此 hook 中
 */
export function useSearch<T extends Record<string, any>>(service: SearchService<T>, options?: UseSearchOptions) {
  if (!(options && options.dataKeyName)) {
    options = {
      dataKeyName: 'data',
    }
  }

  // 搜索框内容
  const searchText = ref('')
  // 是否处于搜索状态
  const isOpenSearch = ref(false)
  // 搜索中
  const searching = ref(false)
  // 搜索结果
  const searchResult = ref<T[]>([]) as Ref<T[]>

  // 搜索请求
  const fetchSearchResult = useThrottleFn(async () => {
    searching.value = true
    try {
      const res = await service()
      if (res.code === 1) {
        searchResult.value = res.data[options!.dataKeyName!] as T[]
        searching.value = false
      }
      else {
        uni.showToast({ title: res.msg, icon: 'none' })
        searching.value = false
      }
    }
    catch (error: any) {
      uni.showToast({ title: `搜索失败，${error.message}`, icon: 'none' })
      searching.value = false
    }
  }, 1000)

  return { searchText, isOpenSearch, searching, searchResult, fetchSearchResult }
}
